package com.igeek.boot.config;

import com.igeek.boot.servlet.MyFilter;
import com.igeek.boot.servlet.MyListener;
import com.igeek.boot.servlet.MyServlet;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * SpringBoot定制
 *
 * 方式一：在application.yml配置文件
 * 开启配置绑定 @EnableConfigurationProperties(ServerProperties.class)
 * @ConfigurationProperties(prefix = "server")
 * 使用场景：在配置文件中，通过前缀.属性=值
 * 例如：
 * server:
 *   port: 8899
 *
 * 方式二：在配置文件中
 * 条件装配 @ConditionalOnMissingBean(name = DispatcherServlet.MULTIPART_RESOLVER_BEAN_NAME)
 * 使用场景：@Configuration + @Bean 组合进行替换底层组件
 * 例如：
 * @Bean
 * public MultipartResolver multipartResolver(MultipartResolver resolver) {
 *      return resolver;
 * }
 *
 * 方式三：在底层的自动配置类  XxxCustomizer
 * @Bean
 * @ConditionalOnClass(name = "org.apache.catalina.startup.Tomcat")
 * public TomcatServletWebServerFactoryCustomizer tomcatServletWebServerFactoryCustomizer(ServerProperties serverProperties) {
 * 		return new TomcatServletWebServerFactoryCustomizer(serverProperties);
 * }
 *
 *
 * 总结：
 * 引入场景starter --> XxxAutoConfiguration生效 --> @Bean导入xxx组件 --> 绑定XxxProperties --> 配置文件前缀操作属性
 */
@Configuration
public class WebConfig {



    //注册MyServlet
    @Bean
    public ServletRegistrationBean servletRegistrationBean(){
        //第一个参数：自定义的Servlet   第二个参数：处理的请求路径
        ServletRegistrationBean registrationBean = new ServletRegistrationBean(new MyServlet() , "/myServlet","/first");
        //设置Servlet的启动顺序
        registrationBean.setLoadOnStartup(1);
        return registrationBean;
    }

    //注册MyFilter
    @Bean
    public FilterRegistrationBean filterRegistrationBean(){
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        //将自定义的过滤器设置
        registrationBean.setFilter(new MyFilter());
        //设置过滤器的过滤路径
        registrationBean.setUrlPatterns(Stream.of("/css/*","/js/*").collect(Collectors.toList()));
        return registrationBean;
    }

    //注册MyListener
    @Bean
    public ServletListenerRegistrationBean servletListenerRegistrationBean(){
        ServletListenerRegistrationBean registrationBean = new ServletListenerRegistrationBean(new MyListener());
        return registrationBean;
    }
}
